package com.vanzo.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

/**
 * Created by tisen on 2018/2/24.
 */

public class Talkie {
    public static final String TAG = "Talkie";
    public static final String PACKAGE_NAME = "com.vanzo.talkie2";
    public static final String CLASS_NAME = "com.vanzo.test.MessengerService";

    private Context mContext;
    private ComponentName mComponentName = new ComponentName(PACKAGE_NAME, CLASS_NAME);

    private Messenger mMessenger = null;
    private boolean mBound = false;

    public Talkie(Context mContext) {
        this.mContext = mContext;
    }

    public boolean isBind() {
        return mBound;
    }

    public void bind() {
        Intent intent = new Intent();
        intent.setClass(mContext, MessengerService.class);
//        intent.setComponent(mComponentName);
        mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMessenger = new Messenger(service);
            mBound = true;
            sendPttDown();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMessenger = null;
            mBound = false;
        }
    };

    public void unbind() {
        mContext.unbindService(connection);
    }

    private void sendMessage(Message msg) {
        if (!mBound) return;
        try {
            mMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void sendPttDown() {
        Message msg = new Message();
        msg.what = 1;
        msg.replyTo = mReceiverMessenger;
        sendMessage(msg);
    }

    public void sendPttUp() {
        Message msg = new Message();
        msg.what = 2;
        msg.replyTo = mReceiverMessenger;
        sendMessage(msg);
    }

    private void sendMessageTest() throws RemoteException {
        Message msg = new Message();
        msg.what = 1;
        msg.replyTo = mReceiverMessenger;
        mMessenger.send(msg);
    }

    private Messenger mReceiverMessenger = new Messenger(new ReceiverHandler());

    class ReceiverHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Log.w(TAG, "receiver message ptt down");
                    break;
                case 2:
                    Log.w(TAG, "receiver message ptt up");
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
}
